
package go.tetris.client;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;


public final class TetrisPanel extends Composite {
	private static final int CUBE_SIZE = 16;
	private static final String CUBE_SET = "8blocks-gw-16.png";
	private static Cube tcubes[][];
	private static Grid grid;

	public TetrisPanel(int width, int height) {
		grid = new Grid(height, width);
		tcubes = new Cube[getWidth()][getHeight()];
		for (int i = 0; i != getWidth(); ++i) {
			for (int j = 0; j != getHeight(); ++j) {
				tcubes[i][j] = new Cube();
				grid.setWidget(j, i, tcubes[i][j]);
			}
		}
		grid.setCellPadding(0);
		grid.setCellSpacing(0);
		grid.setStyleName("field");
		clear();
		initWidget(grid);
	}

	public static void clear() {
		for (int i = 0; i != getWidth(); ++i) {
			for (int j = 0; j != getHeight(); ++j) {
				tcubes[i][j].setValue(0);
				drawTile(i, j, 0);
			}
		}
	}

	public static void clearLine(int y) {
		for (int i = 0; i != y; ++i) {
			for (int j = 0; j != getWidth(); ++j) {
				int tile = tcubes[j][y - i - 1].getValue();
				if (tcubes[j][y - i].getValue() != tile) {
					tcubes[j][y - i].setValue(tile);
					drawTile(j, y - i, tile);
				}
				if (y - i - 1 == 0 && tile != 0) {
					tcubes[j][0].setValue(0);
					drawTile(j, 0, 0);
				}
			}
		}
	}

	public static boolean collisionCheck(int x, int y) {
		if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight()
				|| tcubes[x][y].getValue() != 0) {
			return true;
		} else {
			return false;
		}
	}

	public static void drawTile(int x, int y, int n) {
		tcubes[x][y].draw(n);
	}

	public static int getHeight() {
		return grid.getRowCount();
	}

	public static int getWidth() {
		return grid.getColumnCount();
	}

	public static boolean isLine(int y) {
		if (y < getHeight()) {
			for (int i = 0; i != getWidth(); ++i) {
				if (tcubes[i][y].getValue() == 0) {
					return false;
				}
			}
			return true;
		} else {
			return false;
		}
	}

	public static void setTile(int x, int y, int tile) {
		tcubes[x][y].setValue(tile);
	}
}
